<template>
  <div
    v-if="detail"
    class="detail overflow-hidden">
    <div class="header">
      <el-row>
        <el-col :span="12">
          <div class="flex items-center">
            <el-avatar
              shape="square"
              :src="detail.avatar"
              :icon="User"></el-avatar>
            <div class="flex-1 ml-[10px]">
              <div class="name mb-[5px] flex items-center">
                <span class="font-bold">{{ detail.nickname }}</span>
                <span
                  v-if="detail.external_userid"
                  class="text-[green] text-[12px] ml-[10px]"
                  >@微信</span
                >
                <el-icon
                  class="ml-[5px] text-[12px]"
                  @click.stop="copyEvent(detail.nickname)"
                  ><CopyDocument
                /></el-icon>
              </div>
              <el-space>
                <el-tag size="small">标签</el-tag>
                <el-popover
                  placement="bottom"
                  :width="260"
                  trigger="click">
                  <template #reference>
                    <el-tag size="small">···</el-tag>
                  </template>
                  <el-space wrap>
                    <el-tag
                      size="small"
                      v-for="(item, index) in [1, 2, 3, 4, 5]"
                      :key="index"
                      >标签</el-tag
                    >
                  </el-space>
                </el-popover>
                <el-button
                  type="primary"
                  size="small"
                  text
                  :icon="Edit"
                  >编辑</el-button
                >
              </el-space>
            </div>
          </div>
        </el-col>
        <el-col :span="12"></el-col>
      </el-row>
      <el-row
        class="mt-[10px]"
        :gutter="10">
        <el-col :span="6">
          <div class="item">
            <div class="label">会员等级</div>
            <div class="value">
              <el-dropdown @command="handleEditLevel">
                <div class="flex items-center">
                  {{ detail.level }}
                  <el-icon class="ml-[5px]"><edit /></el-icon>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="(item, index) in levelList"
                      :key="index"
                      :command="item.value"
                      >{{ item.label }}</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="item">
            <div class="label">归属门店</div>
            <div class="value" style="margin-top: 2px;">
              <!-- <div class="flex items-center">
                <div>{{ detail.store_name || "--" }}</div>
                <el-icon class="ml-[5px]" @click="handleEditStore"><edit /></el-icon>
              </div> -->
              <el-select
                v-model="detail.store_id"
                filterable
                size="small"
                placeholder="请选择归属门店"
                @change="handleEditStore"
              >
                <el-option
                  v-for="(item) in storeList"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                />
              </el-select>
              <!-- <el-dropdown @command="handleEditStore" max-height="400px">
                <div class="flex items-center">
                  {{ detail.store_name || "--" }}
                  <el-icon class="ml-[5px]"><edit /></el-icon>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="(item, index) in storeList"
                      :key="index"
                      :command="item.id"
                      >{{ item.title || "--" }}</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown> -->
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="item">
            <div class="label">已加微信</div>
            <div class="value">
              <span>未知</span>
              <el-popover
                v-if="false"
                placement="bottom"
                :width="340"
                trigger="click">
                <template #reference>
                  <span
                    >已加好友
                    <el-icon><arrow-down /></el-icon>
                  </span>
                </template>
                <el-card
                  class="mb-[10px]"
                  :shadow="false"
                  v-for="(item, index) in [1, 2, 2, 2]"
                  :key="index">
                  <div class="flex">
                    <el-avatar
                      shape="square"
                      :icon="User"></el-avatar>
                    <div class="flex-1 ml-[10px]">
                      <div class="text-[14px] font-bold">导购姓名</div>
                      <div class="text-[12px] text-[#999] mt-[5px]">
                        部门：所属部门
                      </div>
                      <div class="text-[12px] text-[#999]">
                        企业微信：企业微信
                      </div>
                      <div class="text-[12px] text-[#999]">
                        最近添加时间：2024-11-22 14:06:18
                      </div>
                    </div>
                  </div>
                </el-card>
              </el-popover>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="item">
            <div class="label">所在群聊</div>
            <div class="value">
              <span>未知</span>
              <el-popover
                v-if="false"
                placement="bottom"
                :width="340"
                trigger="click">
                <template #reference>
                  <span
                    >已入群
                    <el-icon><arrow-down /></el-icon>
                  </span>
                </template>
                <el-card
                  class="mb-[10px]"
                  :shadow="false"
                  v-for="(item, index) in [1, 2, 2, 2]"
                  :key="index">
                  <div class="flex">
                    <el-avatar
                      shape="square"
                      :icon="User"></el-avatar>
                    <div class="flex-1 ml-[10px]">
                      <div class="text-[14px] font-bold">群名称</div>
                      <div class="text-[12px] text-[#999] mt-[5px]">
                        群主：所属部门
                      </div>
                      <div class="text-[12px] text-[#999]">部门：所属部门</div>
                      <div class="text-[12px] text-[#999]">
                        企业微信：企业微信
                      </div>
                      <div class="text-[12px] text-[#999]">
                        最近添加时间：2024-11-22 14:06:18
                      </div>
                    </div>
                  </div>
                </el-card>
              </el-popover>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-tabs v-model="activeName">
      <el-tab-pane label="客户信息" name="info">
        <el-row class="title">
          <div class="flex-1">基本信息</div>

          <el-button
            v-if="!isEdit"
            type="primary"
            text
            :icon="Edit"
            @click="isEdit = true"
            >编辑</el-button
          >
          <div v-else>
            <el-button
              size="small"
              @click="handleEditCancel"
              >取消</el-button
            >
            <el-button
              size="small"
              type="primary"
              @click="handleEditConfirm"
              >保存</el-button
            >
          </div>
        </el-row>
        <el-form
          class="mt-[20px]"
          label-width="100px"
          label-position="left">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户ID">
                <el-input
                  v-if="isEdit"
                  v-model="detail.id"
                  :disabled="true"></el-input>
                <span v-else>{{ detail.id }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="微信昵称">
                <el-input
                  v-if="isEdit"
                  v-model="detail.nickname"
                  :disabled="true"></el-input>
                <span v-else>{{ detail.nickname || "--" }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码">
                <el-input
                  v-if="isEdit"
                  v-model="detail.mobile"
                  :disabled="false"
                  placeholder="请输入手机号"></el-input>
                <span v-else>{{ detail.mobile || "--" }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别">
                <el-select
                  v-if="isEdit"
                  v-model="detail.sex"
                  :disabled="false"
                  placeholder="请选择性别">
                  <el-option
                    label="男"
                    :value="1"></el-option>
                  <el-option
                    label="女"
                    :value="2"></el-option>
                  <el-option
                    label="未知"
                    :value="0"></el-option>
                </el-select>
                <span v-else>{{ ["未知", "男", "女"][detail.sex] }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄">
                <el-input
                  v-if="isEdit"
                  v-model="detail.age"
                  :disabled="false"
                  placeholder="请输入年龄"></el-input>
                <span v-else>{{ detail.age || "--" }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审核状态">
                <el-select
                  v-if="isEdit"
                  v-model="detail.status"
                  :disabled="false"
                  placeholder="请选择审核状态">
                  <el-option
                    label="已通过"
                    :value="1"></el-option>
                  <el-option
                    label="审核中"
                    :value="2"></el-option>
                  <el-option
                    label="已拒绝"
                    :value="3"></el-option>
                  <el-option
                    label="黑名单"
                    :value="-1"></el-option>
                </el-select>
                <span v-else>{{
                  {
                    "-1": "黑名单",
                    1: "已通过",
                    2: "审核中",
                    3: "已拒绝",
                  }[detail.status]
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="聊天状态">
                <el-select
                  v-if="isEdit"
                  v-model="detail.chat_ok"
                  :disabled="false"
                  placeholder="请选择聊天状态">
                  <el-option
                    label="已禁言"
                    :value="0"></el-option>
                  <el-option
                    label="可聊天"
                    :value="1"></el-option>
                </el-select>
                <span v-else>{{
                  ["已禁言", "可聊天"][detail.chat_ok || 0]
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="区域限制">
                <el-select
                  v-if="isEdit"
                  v-model="detail.is_freedom"
                  :disabled="false"
                  placeholder="请选择区域限制">
                  <el-option
                    label="已限制"
                    :value="0"></el-option>
                  <el-option
                    label="无限制"
                    :value="1"></el-option>
                </el-select>
                <span v-else>{{
                  ["已限制", "无限制"][detail.is_freedom || 0]
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户IP">
                <el-input
                  v-if="isEdit"
                  v-model="detail.ip"
                  :disabled="true"></el-input>
                <span v-else>{{ detail.ip || "--" }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="IP地址">
                <el-input
                  v-if="isEdit"
                  v-model="detail.ip_address"
                  :disabled="true"></el-input>
                <span v-else>{{ detail.ip_address || "--" }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="加入时间">
                <el-input
                  v-if="isEdit"
                  v-model="detail.reg_time"
                  :disabled="true"></el-input>
                <span v-else>{{
                  detail.reg_time
                    ? dayjs(detail.reg_time * 1000).format(
                        "YYYY-MM-DD HH:mm:ss"
                      )
                    : "--"
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最近答题时间">
                <el-input
                  v-if="isEdit"
                  :value="format(detail.last_join_time || 0)"
                  :disabled="true"></el-input>
                <span v-else>{{ format(detail.last_join_time || 0) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="行为轨迹" name="trajectory">
        <el-timeline
          class="pl-[5px] mb-[20px]"
          v-for="(item, index) in travelList"
          :key="index">
          <el-timeline-item
            :timestamp="item.key"
            placement="top"
            type="primary">
          </el-timeline-item>
          <template
            v-for="(s, i) in item.value"
            :key="i">
            <el-timeline-item
              placement="top"
              center>
              <el-card>
                <div class="flex items-center">
                  <div class="flex-1 font-bold">
                    参与活动: {{ s.activity?.title }}
                  </div>
                  <div class="text-[#999] flex items-center">
                    <el-icon><AlarmClock /></el-icon>
                    <span>{{
                      dayjs(s.play_start_time * 1000).format(
                        "YYYY/MM/DD HH:mm:ss"
                      )
                    }}</span>
                    <span class="pl-[10px] pr-[10px]">至</span>
                    <span>{{
                      dayjs(s.play_end_time * 1000).format(
                        "YYYY/MM/DD HH:mm:ss"
                      )
                    }}</span>
                  </div>
                </div>
                <el-row
                  class="mt-[5px] text-[#666] text-[12px]"
                  :gutter="15">
                  <el-col :span="6"
                    >时长：{{ Math.floor(s.num / 60) }}分{{
                      Math.floor(s.num % 60)
                    }}秒</el-col
                  >
                  <el-col :span="6">红包情况：
                    <el-tag
                      v-if="s.red_status === 1"
                      type="success">
                      已领取
                    </el-tag>
                    <el-tag
                      v-if="s.red_status === 2"
                      type="error">
                      发放失败
                    </el-tag>
                    <el-tag
                      v-if="s.red_status === 3"
                      type="warning">
                      待领取
                    </el-tag>
                  </el-col>
                  <el-col :span="6"
                    >奖励：{{ s.money }}元/{{ s.jifen }}积分</el-col
                  >
                </el-row>
                <el-row
                  class="mt-[5px] text-[#666] text-[12px]"
                  :gutter="15">
                  <el-col :span="6" class="storidText"
                    >门店：{{ s.store_id > 0 ? s.store.title : '平台' }}</el-col
                  >
                  <el-col :span="6"
                    >答题次数：{{ s.dati_num }}次</el-col
                  >
                  <el-col :span="6"
                    >正确数：{{ s.is_right }}</el-col
                  >
                </el-row>
              </el-card>
            </el-timeline-item>
          </template>
        </el-timeline>
      </el-tab-pane>
      <!-- <el-tab-pane label="跟进记录"></el-tab-pane> -->
    </el-tabs>
  </div>
</template>
<script lang="ts" setup>
import {
  getLevelListApi,
  getStoreAllApi,
  getTravelListApi,
  getUserDetailApi,
  updateUserApi,
} from "@/addon/htscrm/api";
import { t } from "@/lang";
import { Edit, ArrowDown, User } from "@element-plus/icons-vue";
import { useClipboard } from "@vueuse/core";
import { dayjs, ElMessage } from "element-plus";
import { ref, watch } from "vue";

const isEdit = ref(false);
const detail = ref<IUserItem>();
const storeList = ref<IStoreItem[]>([]);
const levelList = ref<any[]>([]);
const travelList = ref<ITravelItem[]>([]);
const activeName = ref("info");
function init(row: IUserItem) {
  isEdit.value = false;
  getUserDetail(row.id);
  getStoreList();
  getLevelList();
}

async function getUserDetail(id: IUserItem["id"]) {
  const res = await getUserDetailApi(id);
  detail.value = res.data;
}
async function getStoreList() {
  const res = await getStoreAllApi();
  storeList.value = [
    {
      id: 0,
      store_id: 0,
      title: '平台'
    } as IStoreItem,
    ...res.data
  ];
}

async function getLevelList() {
  const res = await getLevelListApi();

  levelList.value = res.data.map((item) => {
    return {
      label: item.name,
      value: item.id,
    };
  });
}
async function getTravelList(id: any) {
  const res = await getTravelListApi({ id });
  travelList.value = Object.entries(res.data).map(([key, value]) => ({
    key,
    value,
  }));
}

// 复制
const { copy, isSupported, copied } = useClipboard();
const copyEvent = (text: string) => {
  if (!isSupported.value) {
    // ElMessage({
    //     message: t('notSupportCopy'),
    //     type: 'warning'
    // })
  }
  copy(text);
};

watch(copied, () => {
  if (copied.value) {
    ElMessage({
      message: t("copySuccess"),
      type: "success",
    });
  }
});

function format(value: number) {
  if (!value) return "--";
  if (new Date().setHours(0, 0, 0) < value) {
    return "今日";
  }
  const data = parseInt(Date.now() / 1000 + "") - value;
  // 时分秒
  const days = Math.floor(data / (3600 * 24));
  if (days == 1) {
    return "昨日";
  } else {
    return days + "天前";
  }
}

async function handleEditLevel(value: number) {
  console.log(value);
  const res = await updateUserApi({
    id: detail.value?.id,
    level: value,
  });

  if (res.code === 1) {
    ElMessage({
      message: "保存成功",
      type: "success",
    });
    getUserDetail(detail.value?.id);
  }
}
async function handleEditStore(value: number) {
  console.log(value);
  const res = await updateUserApi({
    id: detail.value?.id,
    store_id: value,
  });

  if (res.code === 1) {
    ElMessage({
      message: "保存成功",
      type: "success",
    });
    getUserDetail(detail.value?.id);
  }
}
async function handleEditConfirm() {
  // const res = await updateUserApi({
  //   id: detail.value?.id,
  //   mobile: detail.value?.mobile,
  //   sex: detail.value?.sex,
  //   age: detail.value?.age,
  //   status: detail.value?.status,
  // });
  const obj: any = {
    ...detail.value,
  };
  delete obj.from_user_name;
  delete obj.from_user_avatar;
  delete obj.level_id;
  delete obj.level;
  const res = await updateUserApi(obj);

  if (res.code === 1) {
    ElMessage({
      message: "保存成功",
      type: "success",
    });
    isEdit.value = false;
    getUserDetail(detail.value?.id);
  }
}
async function handleEditCancel() {
  isEdit.value = false;
  getUserDetail(detail.value?.id);
}

defineExpose({
  init,
  getTravelList
});
</script>

<style lang="scss" scoped>
// :deep(.el-select--small .el-select__wrapper) {
//   padding-top: 0px !important;
//   padding-bottom: 0px !important;
// }

.storidText{
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-select {
  width: 100%;
}
.el-avatar {
  width: 50px;
  height: 50px;
  background-color: var(--el-color-primary-light-5);
}
:deep() {
  --el-card-padding: 10px;
}
.header {
  // background-color: var(--el-bg-color-page);
  // padding: 15px;
  // border-radius: 5px;

  .name {
    .el-icon {
      cursor: pointer;
    }
  }

  .item {
    padding: 10px 15px;
    border-radius: 5px;
    background-color: var(--el-color-primary-light-9);
    .label {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }

    .value {
      font-size: 14px;
      color: var(--el-text-color-regular);
      margin-top: 5px;
    }
  }
}
.title {
  align-items: center;
  &::before {
    content: "";
    width: 4px;
    height: 15px;
    background-color: var(--el-color-primary);
    margin-right: 5px;
  }
}
</style>
